<?php
	include('db-api/txt-db-api.php');
	
	function create_cookie()
	{
		$name = $_SESSION['user'];
		$position = $_SESSION['position'];
		$username = $_SESSION['username'];
		setcookie("eam_eclass_login[user]", $name, time() + 3600 * 24 * 30);
		setcookie("eam_eclass_login[position]", $position, time() + 3600 * 24 * 30);
		setcookie("eam_eclass_login[username]", $username, time() + 3600 * 24 * 30);
	}
	
	function user_found()
	{
		if(isset($_SESSION['user']))
			return true;
		if(!isset($_COOKIE['eam_eclass_login']))
			return false;
		foreach($_COOKIE['eam_eclass_login'] as $name => $value)
			$_SESSION[$name] = $value;
		return true;
	}
	
	function login(&$error)
	{
		if($_POST['username'] == '')
			$error = '<span class="error">* Δε δώσατε όνομα χρήστη</span>';
		if($_POST['pass'] == '')
			$error = $error . '<br /><span class="error">* Δε δώσατε συνθηματικό</span>';
		
		if($error != '')
			return;

		$db = new Database('Eclass');
		$rs = $db->executeQuery('SELECT Name, Surname, Username, Password, Position FROM Users');
		while($rs->next())
		{
			list($name, $surname, $username, $pass, $position) = $rs->getCurrentValues();
			if($username == $_POST['username'] && $pass == $_POST['pass'])
			{
				$_SESSION['user'] = $name . ' ' . $surname;
				$_SESSION['position'] = $position;
				$_SESSION['username'] = $username;
				if($_POST['rememberme'] == 'on')
					create_cookie();
				header('Location: index.php');
				break;
			}
		}
		$error = '<span class="error">* Το όνομα χρήστη ή/και το συνθηματικό είναι λανθασμένα<span>';
	}
	
	if(isset($_SESSION['user']))
		header('Location: index.php');
	else
	{
		$error = '';
		if(isset($_GET['action']) && $_GET['action'] == 'login')
			login($error);
	}
?>
